library(survey)
library(dplyr)
library(ggplot2)
library(gridExtra)

# Figure 10.1
summary(factor(df$Q27))
summary(factor(df$Q11)) 

df2 <- df
df2 <- df2[df2$Q11 < 77,]

# Q27T
df2$Q27T <- NA
df2$Q27T[df2$Q27 < 3] <- 1
df2$Q27T[df2$Q27 > 2 & df2$Q27 < 77] <- 0

# Guns in schools P_ASSIGN4
# 1 - Control
# 2 - More Safe
# 3 - Less Safe
# 4 - Divided

df2$gms <- NA
df2$gms[df2$P_ASSIGN4==1] <- 0
df2$gms[df2$P_ASSIGN4==2] <- 1

df2$gls <- NA
df2$gls[df2$P_ASSIGN4==1] <- 0
df2$gls[df2$P_ASSIGN4==3] <- 1

df2$gd <- NA
df2$gd[df2$P_ASSIGN4==1] <- 0
df2$gd[df2$P_ASSIGN4==4] <- 1


# Survey designs
w2_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2
  )


# T-tests
# guns in schools
gms <- svyttest(Q27T~gms, w2_design, na.rm = TRUE)
gls <- svyttest(Q27T~gls, w2_design, na.rm = TRUE)
gd <- svyttest(Q27T~gd, w2_design, na.rm = TRUE)

# Build out plots
# Iran
pt.est <- c(gms$estimate, 
            gls$estimate,
            gd$estimate)
ci.low <- c(gms$conf.int[1], 
            gls$conf.int[1],
            gd$conf.int[1])
ci.high <- c(gms$conf.int[2], 
             gls$conf.int[2],
             gd$conf.int[2])
plot.labs <- c("More Safe","Less Safe", "Divided")
df.plot <- data.frame(Treatment=plot.labs, estimate=pt.est, 
                      lower=ci.low, upper=ci.high)
df.plot$Treatment <- factor(df.plot$Treatment, levels = plot.labs)

ggplot()+
  geom_pointrange(data=df.plot, 
                  mapping = aes(x=Treatment,
                                y=estimate,
                                ymin=lower,
                                ymax=upper),
                  size = 0.5, color = "black")+
  geom_hline(yintercept = 0, color = "red")+
  ylim(-.1,.1)+
  ylab("Difference in Means from Control Condition")+
  xlab("Treatment Condition")+
  theme_bw()

